from flask import Blueprint,jsonify,request
from conf.comm import sqlalchemy_context
from database import *
import json
# 实例化
bp_course = Blueprint('course',__name__)

# 无限极分类构造
def xtree(data):
    if data:
        # 如果有数据[{'id':1},'son':[{'id':'3','son':[{},{}]}]]
        list = []
        tree = {}
        for i in data:
            # id做为key,i做为值放到字典中
            tree[i['id']] = i
        
        # {'1',{'id':1,'name':'小周无忧'},'2':{},}
        for j in data:
            # 判断是否有父id,如果有直接加入list
            if not j['parent']:
                list.append(j)
            else:
                # 有父id
                if 'son' not in tree[j['parent']]:
                tree j['parent']['son'].append[j]
        return list

    else:
        return data
    
# 添加分类
@db_course.route('/cateM'，methods=['POST','GET'])
@sqlalchemy_context()
def cateM():
    if request.method == "POST":
        try:
            # 获取用户信息
            if data:
                data = request.data
            else:
                data = request.form
            # 构造对象
          
            try:
                 params = data['params']
            except :
                  params = ''
            
            cate = Cate(name=data['name'],parent=data['parent'],level=data['level'],params=data['params'])
            # 添加
            db.session.add(cate)
            # 提交
            db.session.commit()
            # 返回结果  
            return jsonify({'code':200})

        except:
            return jsonify({'code':10010})
    else:
        cate = Cate.query.all()
        # 定义空列表
        list = [] 
        if cates:m m
            for i in cates:
                dict = {'id':i.id,'name'i.name,'parent'i.parent,'params'i.params,'lecel'i.level}
                list.append(dict)
        list = xtree(list)
        return jsonify({"code":200,"list":list1})

@db_course.route('/getCateById')
def getCateById():
    pass